package fr.vahren.sriksal.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import fr.vahren.sriksal.dao.IAuthDao;

public class AuthDao extends JdbcDaoSupport implements IAuthDao {

	private static final String REQ_SELECT_USER = "SELECT id_user FROM USER WHERE login=? AND password=?";

	/*
	 * (non-Javadoc)
	 * 
	 * @see fr.vahren.sriksal.dao.impl.IAuthDao#checkPassword(java.lang.String,
	 * java.lang.String)
	 */
	@Override
	public long checkPassword(String login, String password) {
		long id = getJdbcTemplate().queryForLong(REQ_SELECT_USER, login,
				password);
		return id;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see fr.vahren.sriksal.dao.impl.IAuthDao#createUser(java.lang.String,
	 * java.lang.String)
	 */
	@Override
	public long createUser(final String login, final String password) {
		KeyHolder userIdKeyHolder = new GeneratedKeyHolder();
		getJdbcTemplate().update(new PreparedStatementCreator() {
			@Override
			public PreparedStatement createPreparedStatement(Connection arg0)
					throws SQLException {
				PreparedStatement statement = arg0.prepareStatement(
						"INSERT INTO sriksal.USER (login,password) VALUES (?,?)",
						new String[] { "ID_USER" });
				statement.setString(1, login);
				statement.setString(2, password);
				return statement;
			}
		}, userIdKeyHolder);
		return userIdKeyHolder.getKey().longValue();
	}
}
